<!--
  * 实训室耗材入库
  *
  * @Author:    xixi
  * @Date:      2024-11-08 13:31:03
  * @Copyright  🐂🐎bloc
-->
<template>
  <a-modal
      :title="form.id ? '编辑' : '添加'"
      :width="500"
      :open="visibleFlag"
      @cancel="onClose"
      :maskClosable="false"
      :destroyOnClose="true"
  >
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
      <a-form-item label="入库日期" name="entryDate">
        <a-date-picker valueFormat="YYYY-MM-DD" v-model:value="form.entryDate" style="width: 100%"
                       placeholder="入库日期"/>
      </a-form-item>

      <a-form-item label="类别" name="category">
        <!--          <a-input style="width: 100%" v-model:value="form.category" placeholder="类别"  />-->
        <CategoryTree v-model:value="form.category" placeholder="请选择耗材分类"
                      :categoryType="CATEGORY_TYPE_ENUM.category.value"/>
      </a-form-item>
      <a-form-item label="物料代码" name="materialCode">
        <!--          <a-input style="width: 100%" v-model:value="form.materialCode" placeholder="物料代码" @blur="onBlur(form.materialCode)"/>-->
        <a-select
            ref="select"
            v-model:value="form.materialCode"
            style="width: 100%"
            @change="handleChange"
        >
          <a-select-option v-for="item in codeList" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="物料名称" name="materialName">
        <a-input style="width: 100%" v-model:value="form.materialName" placeholder="物料名称"/>
      </a-form-item>
      <a-form-item label="规格型号" name="specificationModel">
        <a-input style="width: 100%" v-model:value="form.specificationModel" placeholder="规格型号"/>
      </a-form-item>
      <a-form-item label="单位" name="unit">
        <a-input style="width: 100%" v-model:value="form.unit" placeholder="单位"/>
      </a-form-item>
      <a-form-item label="采购数量" name="purchaseQuantity">
        <a-input-number style="width: 100%" v-model:value="form.purchaseQuantity" placeholder="采购数量"/>
      </a-form-item>
      <a-form-item label="单价（元）" name="unitPrice">
        <a-input-number style="width: 100%" v-model:value="form.unitPrice" placeholder="单价（元）"/>
      </a-form-item>
      <a-form-item label="总价（元）" name="totalPrice">
        <a-input-number style="width: 100%" v-model:value="form.totalPrice" placeholder="总价（元）"/>
      </a-form-item>
      <a-form-item label="采购途径" name="purchaseChannel">
        <a-input style="width: 100%" v-model:value="form.purchaseChannel" placeholder="采购途径"/>
      </a-form-item>
      <a-form-item label="存放地点" name="storageLocation">
        <a-input style="width: 100%" v-model:value="form.storageLocation" placeholder="存放地点"/>
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-textarea style="width: 100%" v-model:value="form.remark" placeholder="备注"/>
      </a-form-item>
      <a-form-item label="采购人" name="purchaser">
        <!--          <a-input style="width: 100%" v-model:value="form.purchaser" placeholder="采购人" />-->
        <EmployeeSelect ref="employeeSelect" placeholder="请选择部门负责人" width="100%"
                        v-model:value="form.purchaserActualName"/>
      </a-form-item>
      <!--        <a-form-item label="验收人员"  name="inspector" v-privilege="'inventory:accept:query'">-->
      <!--&lt;!&ndash;          <a-input style="width: 100%" v-model:value="form.inspector" placeholder="验收人员" />&ndash;&gt;-->
      <!--          <EmployeeSelect ref="employeeSelect" placeholder="请选择部门负责人" width="100%" v-model:value="form.inspectorActualName"/>-->
      <!--        </a-form-item>-->
      <a-form-item label="仓库管理员" name="warehouseManager">
        <!--          <a-input style="width: 100%" v-model:value="form.warehouseManager" placeholder="仓库管理员" />-->
        <EmployeeSelect ref="employeeSelect" placeholder="请选择部门负责人" width="100%"
                        v-model:value="form.warehouseManagerActualName"/>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
import {reactive, ref, nextTick, toRefs, watch, onMounted} from 'vue';
import _ from 'lodash';
import {message} from 'ant-design-vue';
import {SmartLoading} from '/@/components/framework/smart-loading';
import {consumablesInventoryApi} from '/@/api/business/consumables-inventory/consumables-inventory-api';
import {smartSentry} from '/@/lib/smart-sentry';
import EmployeeSelect from '/@/components/system/employee-select/index.vue';
import {useUserStore} from "/@/store/modules/system/user.js";
import {fabricMaterialsApi} from "/@/api/business/fabric-materials/fabric-materials-api.js";
import CategoryTree from '/@/components/business/category-tree-select/index.vue';
// ------------------------ 事件 ------------------------

const emits = defineEmits(['reloadList']);

const userInfo = useUserStore();

const acceptUser = userInfo.actualName;
const acceptId = userInfo.employeeId;

const CATEGORY_TYPE_ENUM = {
  category: {
    value: 2,
    desc: '类别',
  },
}

// ------------------------ 显示与隐藏 ------------------------
// 是否显示
const visibleFlag = ref(false);

function show(rowData) {
  Object.assign(form, formDefault);
  if (rowData && !_.isEmpty(rowData)) {
    Object.assign(form, rowData);
  }
  form.inspectorActualName = acceptUser;
  form.inspector = acceptId;
  // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
  // if (form.status && form.status.length > 0) {
  //   form.status = form.status.map((e) => e.valueCode);
  // }
  visibleFlag.value = true;
  nextTick(() => {
    formRef.value.clearValidate();
  });
}

function onClose() {
  Object.assign(form, formDefault);
  visibleFlag.value = false;
}

// ------------------------ 表单 ------------------------

// 组件ref
const formRef = ref();
const employeeSelect = ref();
const defaultDepartmentForm = {
  managerId: undefined, //部门负责人
};


let formState = reactive({
  ...defaultDepartmentForm,
});


const formDefault = {
  id: undefined,
  entryDate: undefined, //入库日期
  serialNumber: undefined, //序号
  category: undefined, //类别
  materialCode: undefined, //物料代码
  materialName: undefined, //物料名称
  specificationModel: undefined, //规格型号
  purchaseQuantity: undefined, //采购数量
  unitPrice: undefined, //单价（元）
  totalPrice: undefined, //总价（元）
  purchaseChannel: undefined, //采购途径
  storageLocation: undefined, //存放地点
  remark: undefined, //备注
  actualName: undefined,
  mankind: undefined,
  unit: undefined,
  actualAdmin: undefined,
  warehouseManagerActualName: undefined,
  purchaserActualName: undefined,
  inspectorActualName: undefined
};

let form = reactive({...formDefault});

const rules = {
  entryDate: [{required: true, message: '入库日期 必填'}],

  category: [{required: true, message: '类别 必填'}],
  materialCode: [{required: true, message: '物料代码 必填'}],
  materialName: [{required: true, message: '物料名称 必填'}],
  specificationModel: [{required: true, message: '规格型号 必填'}],
  purchaseQuantity: [{required: true, message: '采购数量 必填'}],
  unitPrice: [{required: true, message: '单价（元） 必填'}],
  totalPrice: [{required: true, message: '总价（元） 必填'}],
  purchaseChannel: [{required: true, message: '采购途径 必填'}],
  storageLocation: [{required: true, message: '存放地点 必填'}],
  actualName: [{required: true, message: '采购人 必填'}],
  mankind: [{required: true, message: '验收人员 必填'}],

};


// 点击确定，验证表单
async function onSubmit() {
  try {
    await formRef.value.validateFields();
    save();
  } catch (err) {
    message.error('参数验证错误，请仔细填写表单数据!');
  }
}

//失去焦点
async function onBlur(fabricMaterialCode) {
  if (!fabricMaterialCode) return;
  try {
    await fabricMaterialsApi.MaterialInfo(fabricMaterialCode).then((res) => {

      if (res.code === 0) {
        form.materialName = res.data.fabricMaterialName;
        form.specificationModel = res.data.specModel;
        form.unitPrice = res.data.unitPrice;
        form.purchaseQuantity = res.data.quantity;
        form.purchaseChannel = res.data.purchaseWay;
        form.storageLocation = res.data.storageLocation;
        form.unit = res.data.unit;
        form.id = res.data.id;
      }
    })
  } catch (err) {
    message.error('参数验证错误，请仔细填写表单数据!');
  }
}

watch(() => form.purchaseQuantity, () => {
  form.totalPrice = form.unitPrice * form.purchaseQuantity;
}, {deep: true})
// 新建、编辑API

//获取所有物料代码
const codeList = ref()
const handleChange = (value) => {
  onBlur(value)
};

async function getMaterialCode() {
  try {
    await fabricMaterialsApi.getAllFabricMaterialCode().then((res) => {
      if (res.code === 0) {
        codeList.value = res.data;

      }
    })
  } catch (err) {
    message.error('参数验证错误，请仔细填写表单数据!');
  }
}

onMounted(() => {
  getMaterialCode();
  codeList.value = Array.from(new Set(codeList.value))
})

async function save() {
  SmartLoading.show();
  const fromNew = {...form, warehouseManager: form.warehouseManagerActualName, purchaser: form.purchaserActualName}
  try {
    if (form.id) {
      await consumablesInventoryApi.update(fromNew);
    } else {
      await consumablesInventoryApi.add(fromNew);
    }
    message.success('操作成功');
    emits('reloadList');
    onClose();
  } catch (err) {
    smartSentry.captureError(err);
  } finally {
    SmartLoading.hide();
  }
}

defineExpose({
  show,
});


</script>
